package com.lam.mall.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lam.common.components.file.service.FileService;
import com.lam.common.utils.CollectionUtil;
import com.lam.common.utils.StringUtils;
import com.lam.common.validate.ValidateUtil;
import com.lam.mall.entity.Category;
import com.lam.mall.mapper.CategoryMapper;
import com.lam.mall.param.CategoryParam;
import com.lam.mall.service.CategoryService;

/**
 * 产品类目Service业务层处理
 * 
 * @author admin
 * @date 2023-04-20
 */
@Service
public class CategoryServiceImpl  implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private FileService fileService;

    /**
     * 查询产品类目
     * 
     * @param id ID
     * @return 单个对象
     */
    @Override
    @Transactional(readOnly = true)
    public Category selectById(String id) {

        return categoryMapper.selectById(id);
    }

    /**
     * 查询产品类目列表
     * 
     * @param param
     * @return 
     */
    @Override
    @Transactional(readOnly = true)
    public List<Category> selectList(CategoryParam param) {
    
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();

        //关键字查询
        if(StringUtils.isNotBlank(param.getKeywords())) {
            queryWrapper.and(wr->{
                wr.or().like("category_name", param.getKeywords());
            });
        }
        
        queryWrapper.eq(Objects.nonNull(param.getParentId()), "parent_id", param.getParentId());
        queryWrapper.eq(Objects.nonNull(param.getShopId()), "shop_id", param.getShopId());
        queryWrapper.eq(Objects.nonNull(param.getGrade()), "grade", param.getGrade());
        queryWrapper.like(StringUtils.isNotBlank(param.getCategoryNameKey()), "category_name", param.getCategoryNameKey());
        queryWrapper.eq(StringUtils.isNotBlank(param.getCategoryName()), "category_name", param.getCategoryName());
        queryWrapper.eq(Objects.nonNull(param.getStatus()), "status", param.getStatus());

        return categoryMapper.selectList(queryWrapper);
    }

    /**
     * 新增产品类目
     * 
     * @param category 
     * @return 
     */
    @Override
    @Transactional
    public int insert(Category category) {
    
    	categoryMapper.insert(category);
    	insertBrandsAndAttributes(category);
    	fileService.updateUseFlagByFileName(category.getPic());
        return 1;
    }

    /**
     * 修改产品类目
     * 
     * @param category 
     * @return 
     */
    @Override
    @Transactional
    public int update(Category category) {
    
		category.setUpdateTime(new Date());
		// 保存分类信息
		categoryMapper.updateById(category);
		// 先删除后增加
		deleteBrandsAndAttributes(category.getId());
		insertBrandsAndAttributes(category);
		fileService.updateUseFlagByFileName(category.getPic());
        return 1;
    }

    /**
     * 删除产品类目信息
     * 
     * @param idStr ID，多个用逗号分隔
     * @return 
     */
    @Override
    @Transactional
    public int deleteById(String idStr) {
    
        if(StringUtils.isBlank(idStr)) {
            return 0;
        }
        
        ValidateUtil.validDataUsed("mall_category", "parent_id", idStr, "请先删除该分类下的子分类");
//        ValidateUtil.validDataUsed("sys_dept_user", "dept_id", idStr, "机构下有用户，不可删除");
        
        categoryMapper.deleteBatchIds(StringUtils.str2List(idStr));
        deleteBrandsAndAttributes(idStr);
        return 1;
    }

	private void deleteBrandsAndAttributes(String categoryId) {
		// 删除所有分类所关联的品牌
//		categoryBrandMapper.deleteByCategoryId(categoryId);
//		// 删除所有分类所关联的参数
//		categoryPropMapper.deleteByCategoryId(categoryId);
	}

	private void insertBrandsAndAttributes(Category category) {
		//保存分类与品牌信息
//		if(CollUtil.isNotEmpty(category.getBrandIds())){
//			categoryBrandMapper.insertCategoryBrand(category.getCategoryId(), category.getBrandIds());
//		}
//
//		//保存分类与参数信息
//		if(CollUtil.isNotEmpty(category.getAttributeIds())){
//			categoryPropMapper.insertCategoryProp(category.getCategoryId(), category.getAttributeIds());
//		}
	}

	@Override
	public List<Category> treeSelect(String shopId, int grade) {
    	List<Category> categories = categoryMapper.selectList(new LambdaQueryWrapper<Category>().le(Category::getGrade,grade).eq(Category::getShopId,shopId));
		return categoryListToTree(categories);
	}

	public List<Category> categoryListToTree(List<Category> categorys){
		if (CollectionUtil.isEmpty(categorys)) {
			return categorys;
		}
		Map<String, List<Category>> categoryMap = categorys.stream().collect(Collectors.groupingBy(Category::getParentId));

		List<Category> rootList = categoryMap.get("0");
		transformCategoryTree(rootList,categoryMap);
		return rootList;
	}

	public void transformCategoryTree(List<Category> categorys,Map<String, List<Category>> categoryMap) {
		for (Category category : categorys) {
			List<Category> nextList = categoryMap.get(category.getId());
			if (CollectionUtil.isEmpty(nextList)) {
				continue;
			}
			// 将排序完成的list设为下一层级
			category.setCategories(nextList);
			// 处理下 下一层级
			transformCategoryTree(nextList, categoryMap);
		}
	}
    
}
